using Microsoft.Xna.Framework;

namespace whereIsTheDonutGame
{
    public class Camera : GameComponent, ICamera
    {
        private Vector3 position;
        private Vector3 target;

        private Vector3 desiredPosition;
        //private Vector3 desiredTarget;
        private Vector3 offsetDistance;

        public Matrix ViewMatrix { get; set; }
        public Matrix ProjectionMatrix { get; set; }


        private IPlayer player;

        public Camera(Game game)
            : base(game)
        {
            player = (IPlayer)Game.Services.GetService(typeof(IPlayer));
            offsetDistance = new Vector3(0, 11, 35);
        }

        public override void Update(GameTime gameTime)
        {
            UpdateWorldPositions();
            UpdateMatrices();
        }

        public void UpdateMatrices()
        {
            this.ViewMatrix = Matrix.CreateLookAt(this.position, this.target, Vector3.Up);

            this.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                                        MathHelper.ToRadians(40.0f),
                                        this.Game.GraphicsDevice.DisplayMode.AspectRatio,
                                        0.1f,
                                        10000.0f);
        }
        public override void Initialize()
        {
            this.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                                        MathHelper.ToRadians(40.0f),
                                        this.Game.GraphicsDevice.DisplayMode.AspectRatio,
                                        0.1f,
                                        10000.0f);

            base.Initialize();
        }

        private void UpdateWorldPositions()
        {

            target = player.Position;
            desiredPosition = Vector3.Transform(offsetDistance, Matrix.CreateRotationY(player.Rotation) * Matrix.CreateTranslation(player.Position));
            position = Vector3.SmoothStep(position, desiredPosition, .15f);
            position = desiredPosition;
        }
    }
}
